package com.activenetwork.util.dropdownmenu;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.activenetwork.listener.ImplicitlyWaitListener;
import com.activenetwork.util.EnvContext;
import com.activenetwork.util.WaitUtil;
import com.activenetwork.util.WebDriverFactory;

public class DropdownMenu {
	protected Logger logger = LoggerFactory.getLogger(DropdownMenu.class);
	protected WebElement field;
	protected WebElement menuDropdown;
	
	public DropdownMenu(WebElement dropdownField){
		field = dropdownField;
		menuDropdown = field.findElement(By.xpath("./following-sibling::span[@class='add-on nexus-combo-dropdown']"));
	}
	
	public void select(String option){
		menuDropdown.click();
		WebElement ul = waitListDisplay();
		if(ul == null){
			throw new RuntimeException("Unable to find the dropdown list display");
		}
		MenuUL menu = new MenuUL(ul);		
		try{
			menu.select(option);
		}catch(NoSuchElementException e){
			logger.error("Unable to find the option " + option + " in dropdown");
			//throw new RuntimeException(e.getMessage());
		}
		
	}
	
	private WebElement waitListDisplay(){
		WebDriver driver = EnvContext.webDriverTL.get();
		WaitUtil waitUtil = new WaitUtil(1500);
		int count = 0;
		WebElement ul = null;
		
		while(true){
			waitUtil.waiting();
			try{
				WebDriverFactory.unwrap((EventFiringWebDriver)driver, new ImplicitlyWaitListener());
				ul = driver.findElement(By.cssSelector("ul.typeahead.dropdown-menu[style*='display: block;']"));
			}catch(NoSuchElementException e){
				count++;
				if(count>10){
					break;
				}else{
					continue;
				}
			}finally{
				WebDriverFactory.wrap((EventFiringWebDriver)driver, new ImplicitlyWaitListener());
			}
			break;
		}
		return ul;
		
	}
	
}
